package com.example.fridaykt.controller

import com.example.fridaykt.common.base.BaseController
import com.example.fridaykt.common.result.R
import com.example.fridaykt.model.SysUser
import com.example.fridaykt.model.copy
import com.example.fridaykt.model.delFlag
import com.example.fridaykt.model.dto.LoginInput
import com.example.fridaykt.model.userId
import com.example.fridaykt.repository.SysUserRepository
import com.example.fridaykt.service.SysUserService
import com.example.fridaykt.utils.CryptoUtil
import com.example.fridaykt.vo.Page
import com.example.fridaykt.vo.UserVO
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.tags.Tag
import org.babyfish.jimmer.sql.kt.ast.expression.valueIn
import org.springframework.web.bind.annotation.*

@RestController
@Tag(name = "用户管理接口")
class SysUserController(
    private val sysUserService: SysUserService,
    private val sysUserRepository: SysUserRepository,
    private val cryptoUtil: CryptoUtil
) : BaseController() {

    @GetMapping("/u")
    @Operation(summary = "查询所有用户")
    fun findAllUser(uservo: UserVO): R {
        val page: Page<SysUser> = sysUserService.getUserList(uservo)
        return R.success(page)
    }

    @Operation(summary = "用户登录")
    @PostMapping("/u/login")
    fun login(@RequestBody user: LoginInput): R {
        return sysUserService.login(user.userName, user.password!!)
    }

    @Operation(summary = "用户注销")
    @GetMapping("/u/logout")
    fun logout(): R {
        return sysUserService.logout()
    }

    @PostMapping("/u")
    @Operation(summary = "新增用户")
    fun addUser(@RequestBody user: SysUser): R {
        val newUser = user.copy {
            password = cryptoUtil.encrypt(user.password)
        }
        sysUserRepository.save(newUser)
        return toAjax(1)
    }

    @Operation(summary = "根据id修改用户")
    @PutMapping("/u")
    fun updateTUser(@RequestBody tUser: SysUser): R {
        val newUser = tUser.copy {
            password = cryptoUtil.encrypt(tUser.password)
        }
        sysUserRepository.update(newUser)
        return toAjax(1)
    }

    @Operation(summary = "根据id删除用户")
    @DeleteMapping("/u/{userid}")
    fun deleteUser(@PathVariable("userid") userid: Long): R {
        sysUserRepository.deleteById(userid)
        return toAjax(1)
    }

    @Operation(summary = "批量删除用户")
    @DeleteMapping("/u")
    fun deleteUsers(@RequestBody vo: UserVO): R {
        sysUserRepository.sql.createUpdate(SysUser::class) {
            set(table.delFlag, "2")
            where(table.userId valueIn vo.key!!.toList())
        }.execute()
        return toAjax(1)
    }

    @GetMapping("/u/{userId}")
    fun findUser(@PathVariable @Parameter(description = "用户编号") userId: Long): R {
        val user = sysUserRepository.findById(userId)
        return R.success(user)
    }
}
